import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull';
import {
  NovelCrawlerService,
  NovelCrawlData,
} from './novel-crawler.service';
import { Novel } from '../entities/novel.entity';
import { NovelParseTask, TaskStatus, TaskType } from '../entities/novel-parse-task.entity';
import { MasterCategory } from '../entities/master-category.entity';
import { CategoryMappingService } from './category-mapping.service';

@Injectable()
export class ImportNovelService {
  private readonly logger = new Logger(ImportNovelService.name);

  constructor(
    private readonly novelCrawlerService: NovelCrawlerService,
    @InjectRepository(Novel)
    private readonly novelRepository: Repository<Novel>,
    @InjectRepository(NovelParseTask)
    private readonly taskRepository: Repository<NovelParseTask>,
    @InjectRepository(MasterCategory)
    private readonly masterCategoryRepository: Repository<MasterCategory>,
    private readonly categoryMappingService: CategoryMappingService,
    @InjectQueue('novel-parse') private readonly novelParseQueue: Queue,
  ) {}

  /**
   * 异步导入小说 - 创建任务并立即返回
   */
  async importNovelAsync(url: string): Promise<{ success: boolean; taskId?: string; error?: string }> {
    try {
      this.logger.log(`开始异步导入小说: ${url}`);

      // 先快速解析小说基本信息
      const crawlResult = await this.novelCrawlerService.parseNovelUrl(url);

      if (!crawlResult.success) {
        return {
          success: false,
          error: crawlResult.error || '解析失败，请检查链接是否正确',
        };
      }

      const novelData = crawlResult.data;

      // 查找或创建母分类
      const masterCategoryId = await this.findOrCreateCategory(
        novelData.category || '其他',
      );

      // 创建小说记录
      const novel = await this.saveNovelToDatabase(novelData, masterCategoryId);

      // 创建任务记录
      const taskId = this.generateTaskId();
      const task = this.taskRepository.create({
        taskId,
        novelId: novel.id,
        taskType: TaskType.NOVEL_PARSE,
        originalUrl: url,
        novelTitle: novelData.title,
        status: TaskStatus.PENDING,
        totalChapters: novelData.chapters || 0,
        processedChapters: 0,
        successChapters: 0,
        failedChapters: 0,
        progress: 0,
        retryCount: 0,
        taskData: {
          platform: novelData.platform,
          category: novelData.category,
        },
      });

      await this.taskRepository.save(task);

      // 添加任务到队列
      await this.novelParseQueue.add('chapter-content', {
        taskId,
        novelId: novel.id,
        originalUrl: url,
        novelTitle: novelData.title,
        platform: novelData.platform,
      }, {
        attempts: 3,
        backoff: {
          type: 'exponential',
          delay: 2000,
        },
        removeOnComplete: 10,
        removeOnFail: 50,
      });

      this.logger.log(`小说导入任务已创建: ${taskId}, 小说ID: ${novel.id}`);

      return {
        success: true,
        taskId,
      };
    } catch (error) {
      this.logger.error(`异步导入小说失败: ${error.message}`, error.stack);
      return {
        success: false,
        error: '导入失败，请重试',
      };
    }
  }

  private generateTaskId(): string {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2, 15);
    return `import_${timestamp}_${random}`;
  }

  private async findOrCreateCategory(categoryName: string): Promise<number> {
    try {
      // 使用分类映射服务映射分类
      const masterCategory = await this.categoryMappingService.mapSiteCategoryToMaster('qidian', categoryName);

      if (masterCategory) {
        this.logger.log(`✅ 分类映射成功: ${categoryName} -> ${masterCategory.name}`);
        return masterCategory.id;
      } else {
        // 如果没有找到映射，使用默认分类
        this.logger.warn(`⚠️  未找到分类映射: ${categoryName}，使用默认分类`);
        return await this.createDefaultCategory(categoryName);
      }
    } catch (error) {
      this.logger.error(`❌ 分类映射处理失败: ${categoryName}`, error);
      // 出错时使用默认分类
      return await this.createDefaultCategory(categoryName);
    }
  }

  /**
   * 创建默认分类（回退方案）
   */
  private async createDefaultCategory(categoryName: string): Promise<number> {
    try {
      // 尝试使用"都市"作为默认分类
      let masterCategory = await this.masterCategoryRepository.findOne({
        where: { name: '都市' },
      });

      if (!masterCategory) {
        // 如果没有都市分类，查找第一个可用的母分类
        masterCategory = await this.masterCategoryRepository.findOne({
          where: { status: 1 },
          order: { sortOrder: 'ASC' },
        });
      }

      if (!masterCategory) {
        this.logger.error(`❌ 系统中没有可用的母分类，无法导入小说`);
        throw new Error('没有可用的母分类');
      }

      this.logger.log(`✅ 使用默认母分类: ${masterCategory.name}`);
      return masterCategory.id;
    } catch (error) {
      this.logger.error(`创建默认分类失败: ${error.message}`, error.stack);
      throw error;
    }
  }

  private async saveNovelToDatabase(
    data: NovelCrawlData,
    masterCategoryId: number,
  ): Promise<Novel> {
    try {
      // 检查是否已存在相同标题和作者的小说
      const existingNovel = await this.novelRepository.findOne({
        where: {
          title: data.title,
          author: data.author,
        },
      });

      if (existingNovel) {
        this.logger.log(`小说已存在，跳过导入: ${data.title} - ${data.author}`);
        return existingNovel;
      }

      // 创建新小说
      const novel = this.novelRepository.create({
        title: data.title,
        author: data.author,
        description: data.description || '',
        coverImage: data.cover || null,
        masterCategoryId: masterCategoryId,
        status: this.getStatusValue(data.status),
        wordCount: this.parseWordCount(data.wordCount),
        tags: data.tags || [],
        platform: data.platform,
        originalUrl: data.originalUrl,
        ratingScore: 0,
        ratingCount: 0,
        readCount: 0,
        favoriteCount: 0,
      });

      const savedNovel = await this.novelRepository.save(novel);
      this.logger.log(
        `小说保存成功: ${savedNovel.title} (ID: ${savedNovel.id})`,
      );

      return savedNovel;
    } catch (error) {
      this.logger.error(`保存小说到数据库失败: ${error.message}`, error.stack);
      throw new Error('保存小说失败');
    }
  }

  private parseWordCount(wordCountStr?: string): number {
    if (!wordCountStr) return 0;

    // 匹配数字，可能包含万字
    const match = wordCountStr.match(/([\d.]+)(万?)/);
    if (!match) return 0;

    const number = parseFloat(match[1]);
    const unit = match[2];

    if (unit === '万') {
      return Math.floor(number * 10000);
    }

    return Math.floor(number);
  }

  private getStatusValue(status?: string): number {
    if (!status) return 1; // 默认连载

    const statusMap = {
      连载中: 1,
      连载: 1,
      已完结: 2,
      完结: 2,
      暂停: 0,
      下架: 0,
    };

    return statusMap[status] || 1;
  }
}